/**
 * 获取选中文本
 * @returns 
 */
function getSelectText(){
	//获取选中区间节点
	let range = window.getSelection().getRangeAt(0);
  let startContainer = range.startContainer;
  let endNodeIndex;
  let startNodeIndex;
  if(startContainer.nodeType == 3){
    startContainer = range.startContainer.parentNode;
    startNodeIndex = [].indexOf.call(window.getSelection().getRangeAt(0).startContainer.parentNode.childNodes,window.getSelection().getRangeAt(0).startContainer);
 
  }
  let endContainer = range.endContainer;
  if(endContainer.nodeType == 3){
    endContainer = range.endContainer.parentNode;
    endNodeIndex = [].indexOf.call(window.getSelection().getRangeAt(0).endContainer.parentNode.childNodes,window.getSelection().getRangeAt(0).endContainer);
  }
	selectText.startContainerPath = getSelectElmentPath(startContainer);
  selectText.startContainerNodeType = range.startContainer.nodeType;
  selectText.startNodeIndex = startNodeIndex;
  selectText.endContainerPath = getSelectElmentPath(endContainer);
  selectText.endContainerNodeType = range.endContainer.nodeType;
  selectText.endNodeIndex = endNodeIndex;
  selectText.startOffset = range.startOffset;
  selectText.endOffset = range.endOffset;
  selectText.baseURI = range.commonAncestorContainer.baseURI;
  console.info(selectText);
	return selectText;
}


/**
 * 选中文本
 */
function selectPageText(selectTextStr){
  let startNode;
  let endNode;
  var selectText = JSON.parse(selectTextStr);
  if(selectText.startContainerNodeType == 3){
    startNode = document.querySelector(selectText.startContainerPath).childNodes[selectText.startNodeIndex];
  }else{
    startNode = document.querySelector(selectText.startContainerPath);
  }
  if(selectText.endContainerNodeType == 3){
    endNode = document.querySelector(selectText.endContainerPath).childNodes[selectText.endNodeIndex];
  }else{
    endNode = document.querySelector(selectText.endContainerPath);
  }
  let range = document.createRange();
  range.setStart(startNode, selectText.startOffset);
  range.setEnd(endNode, selectText.endOffset);
  var span = document.createElement("span");
  span.className = getSelectTextClassName(selectText.selectStyleType);
  span.style.cssText = "color:#ff0000";
  range.surroundContents(span);
}

function getSelectTextClassName(selectType){
  return "select-text-red";
}



//获取节点选择器path
function getSelectElmentPath(el){
  let path = [], parent;
  while (parent = el.parentNode) {
    let tag = el.tagName, siblings;
    path.unshift(
    el.id ? `#${el.id}` : (
      siblings = parent.children,
      [].filter.call(siblings, sibling => sibling.tagName === tag).length === 1 ? tag :
      `${tag}:nth-child(${1+[].indexOf.call(siblings, el)})`
    )
    );
    el = parent;
  };
  return `${path.join(' > ')}`;
}



document.addEventListener(
	'mousedown', 
	function(e) {
		if (e.which != 3) return;
		selectPageText(JSON.stringify(getSelectText()));
	}, 
	false
);
